import { ref } from 'vue'
import { getDataEURework, submitOneEURework, submitAllEURework } from '@/axios/api/picking_team/eu_rework'
import { ElNotification } from 'element-plus';
import * as XLSX from 'xlsx';

//@ts-ignore
import { throttle } from 'lodash'; // 防抖函数
import useEuStore from '@/store//eu';
const euStore = useEuStore();

export default function () {
    // 表格数据
    let tableData = ref([])

    // 当前页数
    let currentPage4 = ref(1);
    // 每页显示条数
    let pageSize4 = ref(100);
    // 总条数
    let total4 = ref(0);

    let sumqty = ref(0)

    // 每页显示条目个数改变时触发
    const handler = () => {
        currentPage4.value = 1;
        getTableData();
    }
    // 当前页数改变时触发
    const getHasUser = () => {
        getTableData();
    }


    // 获取表格数据
    async function getTableData() {
        tableData.value = [];
        sumqty.value = 0;
        try {
            let res: any = await getDataEURework(currentPage4.value, pageSize4.value)
            res.data.sort(function(a:any, b:any) {
                let dateA:any = new Date(a.LotNoDate), dateB:any = new Date(b.LotNoDate);
                return dateA - dateB; // 升序排序
            });
            res.data.forEach((item: any) => {
                if (item.LotNoDate.substring(0, 4) == "1900") {
                    item.LotNoDate = '待派发'
                }
            })
            
            tableData.value = res.data;
            total4.value = res.total||0;
            sumqty.value = res.sumqty;
            return 'ok';
        } catch (error: any) {
            ElNotification({
                title: 'Error',
                message: error,
                type: 'error',
            })
            tableData.value = [];
            sumqty.value = 0;
            return Promise.reject(new Error(error))
        }
    }

    // 刷新
    function refreshData() {
        currentPage4.value = 1;
        getTableData();
        euStore.getData();
    }

    // 节流函数 throttle ,handleClick函数在3000毫秒内只会执行一次
    const refreshData_throttle = throttle(refreshData, 3000, {
        leading: true, // 第一次触发立即执行
        trailing: false // 最后一次触发不执行
    })
    // 单个提交
    async function handlOne(row: any) {
        try {
            await submitOneEURework({ ContractNO: row.ContractNO, CN_Name: row.CN_Name, PCS: row.PCS, Qty: row.Qty });
            refreshData();
           
            return 'ok';
        } catch (error: any) {
            ElNotification({
                title: 'Error',
                message: error,
                type: 'error',
            })
            return Promise.reject(new Error(error))
        }
    }
    // 批量提交
    async function handleAll(multipleSelection: any) {
        if (multipleSelection.length == 0) {
            ElNotification({
                title: 'Error',
                message: '请选择数据',
                type: 'error',
            })
            return Promise.reject(new Error('请选择数据'))
        }
        // 将 multipleSelection 转换为 SubmitData 类型的数据结构
        const submitData = {
            data: multipleSelection
        };
        try {
            await submitAllEURework(submitData);
            refreshData();
            ElNotification({
                title: 'Success',
                message: '提交成功',
                type: 'success',
            });
            return 'ok';
        } catch (error: any) {
            ElNotification({
                title: 'Error',
                message: error,
                type: 'error',
            })
            return Promise.reject(new Error(error))
        }
    }

      // 导出excel
      const exportExcel = async () => {
        if (tableData.value.length == 0) {
            ElNotification({
                title: 'Error',
                message: '没有数据',
                type: 'error',
            })
            return;
        }

        const ws = XLSX.utils.json_to_sheet(tableData.value); // 将数据转换为工作表
        const wb = { Sheets: { 'Data': ws }, SheetNames: ['Data'] }; // 创建工作簿
        const excelBuffer = XLSX.write(wb, { bookType: 'xlsx', type: 'array' }); // 将工作簿转化为二进制缓冲区

        // 创建Blob对象并使用URL.createObjectURL方法生成URL
        const data = new Blob([excelBuffer], { type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet;charset=UTF-8' });
        const url = URL.createObjectURL(data);

        // 创建隐藏的可下载链接
        const link = document.createElement('a');
        link.href = url;
        link.style.display = 'none';
        link.download = 'data.xlsx'; // 设置下载文件名
        document.body.appendChild(link);

        // 触发点击下载
        link.click();
        // 清理
        setTimeout(() => {
            document.body.removeChild(link);
            window.URL.revokeObjectURL(url);
        }, 100);
    }
    return {
        tableData,
        refreshData_throttle,
        handlOne,
        handleAll,
        currentPage4,
        pageSize4,
        total4,
        sumqty,
        handler,
        getHasUser,
        getTableData,
        exportExcel
    }
}